/*
    find usb camera is used to determine *  in /dev/video* by auto scan the path or id. 
*/
#pragma once
#include <iostream>
#include <string>
#include <sstream>

int get_video_id(const std::string search_type, const std::string key_words, std::string &video_port)   
{

    char *buf_line;  
    size_t len = 1024;
    FILE *ptr = NULL; 

    std::string cmd;
    if(search_type == "ID")
    {
        cmd = "ls -l  /dev/v4l/by-id/";  
    }
    else if(search_type == "PATH")
    {
        cmd = "ls -l  /dev/v4l/by-path/";  
    }
    else
    {
        return -1; // keep
    }

    std::cout << "\033[31m" << "Auot scan the video port" << "\033[0m" << std::endl;
    if((ptr=popen(cmd.c_str(), "r"))!=NULL)   
    {
        while(getline(&buf_line, &len, ptr)!= -1)  
        {
           std::stringstream ss;
           ss << buf_line; 
           std::string line = ss.str();
        //    std::cout << line << std::endl;
           if(line.find(key_words) != std::string::npos)
           {
                if(line.find("/video") != std::string::npos)
                {
                    int pos = line.find("/video");
                    // std::cout << "line[pos+6]: " << line[pos+6] << std::endl;
                    int usb_port_num = line[pos+6] - '0';
                    pclose(ptr);   
                    ptr = NULL;   
                    video_port = "/dev/video" + std::to_string(usb_port_num);
                    std::cout << "\033[32m" << "Find the video port: " << video_port << "\033[0m" << std::endl;
                    return usb_port_num;
                }
                else
                {
                    std::cout << "\033[31m" << "NOT FIND video IN " << line << "\033[0m" << std::endl;
                }
           }
           else
           {
                std::cout << "\033[31m" << "NOT FIND "<< key_words << " IN " << line << "\033[0m" << std::endl;
           }   
              
        }   
        pclose(ptr);   
        ptr = NULL;   
    }   
    else  
    {   
        // printf("popen %s error", cmd.c_str());   
        std::cout << "\033[31m" << "popen " << cmd << " error" << "\033[0m" << std::endl;
    }
    return -2; // ERROR
}